package model;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Administrator
 * Date: 2023-01-13
 * Time: 下午 21:37
 */
//用户页面要实现的功能
    //1.新增用户
    //2.根据用户查询用户信息(实现登录的时候)
    //3.根据用户ID来查询用户信息(获取文章的时候,根据博客的userID拿到作者的信息)


public class UserDao {

    public User selectByName(String userName) {
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;

        try {
            //建立连接
            connection = DBUtil.getConnection();
            //构建sql语句
            String sql = "select * from user where userName= ?";
            statement = connection.prepareStatement(sql);
            statement.setString(1,userName);
            //执行sql语句
            resultSet = statement.executeQuery();

            if(resultSet.next()) {
                User user = new User();
                user.setUserID(resultSet.getInt("userID"));
                user.setUserName(resultSet.getString("userName"));
                user.setPassWord(resultSet.getString("passWord"));

                return user;
            }


        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DBUtil.close(connection,statement,resultSet);
        }

        return null;
    }

    public User selectByID(int userID) {
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;

        try {
            //建立连接
            connection = DBUtil.getConnection();
            //构建sql语句
            String sql = "select * from user where userID = ?";
            statement = connection.prepareStatement(sql);
            statement.setInt(1,userID);
            //执行sql语句
            resultSet = statement.executeQuery();

            if(resultSet.next()) {
                User user = new User();
                user.setUserID(resultSet.getInt("userID"));
                user.setUserName(resultSet.getString("userName"));
                user.setPassWord(resultSet.getString("passWord"));

                return user;
            }


        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(connection,statement,resultSet);
        }

        return null;
    }
}
